using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Character : MonoBehaviour
{
    [Header("基本属性")]    
    public float maxHealth;
    public float curretHealth;

    [Header("受伤无敌")]
    public float invulnerableDuration;
    private float invulnerableTimer;
    public bool invulnerable;

    public UnityEvent<Transform> OnTakeDamage;
    public UnityEvent OnDie;
    private void Start()
    {
        curretHealth = maxHealth;
    }

    private void Update()
    {
        if(invulnerable)
        {
            invulnerableTimer -= Time.deltaTime;
            if(invulnerableTimer <= 0)
            {
                invulnerable = false;
            }
        }
    }

    public void TakeDamage(Attack attacker)
    {
        if (invulnerable)
        {
            return;
        }

        if (curretHealth - attacker.damage > 0)
        {
            curretHealth -= attacker.damage;
            TriggerInvulnerable();
            //执行受伤
            OnTakeDamage?.Invoke(attacker.transform);
        }
        else
        {
            curretHealth = 0;
            //die
            OnDie?.Invoke();
        }
    }
    
    private void TriggerInvulnerable()
    {
        if(!invulnerable)
        {
            invulnerable = true;
            invulnerableTimer = invulnerableDuration;
        }
    }
}
